<?php

use Biz\model\ShopCategoryClassify;
use Biz\service\brand\Brand as BrandService;
use Biz\service\BrandPreFecture;
use Biz\service\wiki\Wiki;
use Biz\service\wikiRanking\Ranking;
use Doraemon\cache\Wiki\SearchBrandScore;
use Biz\model\brand\Brand;
use Doraemon\model\Member;
use Doraemon\model\MyFocus;
use Doraemon\service\statSign\Basic as statSign;
use Doraemon\service\WikiBasic\Schedule;
use Doraemon\tools\ActionLog;
use Doraemon\tools\BlockType;
use Doraemon\tools\Hhzurl;

class BrandListAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;

    const DEFAULT_PAGESIZE = 20;
    const MY_FOCUS = -2;//我的关注
    const POPULAR_BRANDS = -1;//热门品牌
    const IS_LOG_EXPOSE = 1;

    /**
     * @throws \Exception
     */
    public function main()
    {

        $data = [];
        $data['is_over'] = 0;

        $page = $this->getRequest()->get('page', 1);
        $classify_id = $this->getRequest()->get('id', '');//分类id
        $classify_name = $this->getRequest()->get('title', '');//分类名称
        $cate_ids = '0';
        if (!$classify_id || !$classify_name) {
            throw new Exception('id或title缺少参数');
        }
        switch ($classify_id) {
            case self::MY_FOCUS:
                //我关注的品牌数据
                $recommend_brands = $this->myFocusBrand($page);
                break;
            case self::POPULAR_BRANDS:
                //热门品牌数据
                $recommend_brands = (array)BrandPreFecture::getRecommendBrands($this->uid, 0, 0,
                    self::DEFAULT_PAGESIZE);
                if (empty($recommend_brands)) {
                    $category = array_column(ShopCategoryClassify::getFirstDeepClassify(), 'id');
                    $categoryId = $category[array_rand($category)];
                    $recommend_brands = SearchBrandScore::getClassifyBrands($categoryId);
                }
                break;
            default:
                //默认处理方式
                $redis = new \Hhz\Redis\newCache(\hhz\constant\redis\redisKeys::KEY_B_CACHE_CATEGORY_CLASSIFY_);
                $cate_ids = $redis->getCache($classify_id);
                $recommend_brands = (array)BrandPreFecture::getRecommendBrands($this->uid, $classify_id, $cate_ids,
                    self::DEFAULT_PAGESIZE);
                if (empty($recommend_brands)) {
                    $recommend_brands = SearchBrandScore::getClassifyBrands($classify_id);
                }
        }

        $brand_ids = array_column($recommend_brands['list'] ?? [], 'obj_id');
        $brand_list = [];
        if ($brand_ids) {
            $total = (int)$recommend_brands['total_num'];
            if ($total <= ($page * self::DEFAULT_PAGESIZE)) {
                $data['is_over'] = 1;
                if ($page != 1) {
                    $curr_num = (int)($total - ($page - 1) * self::DEFAULT_PAGESIZE);
                    $brand_ids = array_slice($brand_ids, 0, $curr_num);
                }
            }

            list($insertIndex, $insertIndexBrandId) = $this->showTclIndex($page, $classify_id);
            if (!is_null($insertIndex) && !is_null($insertIndexBrandId)) {
                $brand_ids[] = $insertIndexBrandId;
            }
            $brand_ids = array_values($brand_ids);
            if ($classify_id != self::MY_FOCUS && $classify_id != self::POPULAR_BRANDS) {
                $cate_ids = explode(',', $cate_ids);
                $wikis = Schedule::getGroupBrandGoods($brand_ids, $cate_ids, 3);
            } else {
                $wikis = Schedule::getGroupBrandGoods($brand_ids, [], 3);
            }
            $wikiIds = [];
            foreach ($wikis as $key => $row) {
                $wiki_ids = array_column($row, 'id');
                $wikiIds = array_merge($wikiIds, $wiki_ids);
            }
            $wikiList = Wiki::getWikiBaseList($wikiIds);
            $wikiList = $this->handleWiki($wikiList, $classify_id);
            $brandWikiList = [];
            foreach ($wikiList as $row) {
                $brandWikiList[$row['brand_id']][] = $row;
            }
            $brandRankingCntMap = Ranking::getCountByBrandIdArr($brand_ids);//获取品牌榜数据
            $brandUserInfos = BrandService::getBrandUserInfos($brand_ids, true, false, true);
            $sort = 0;
            $insertBrandInfo = null;
            foreach ($brandUserInfos as $brandId => $brandUserInfo) {
                $brandWikis = $brandWikiList[$brandId] ?? [];
                if ($brandWikis) {
                    $brand = $brandUserInfo;
                    $brand['wiki_list'] = $brandWikis;
                    $brand['ranking_info'] = [
                        'desc' => "品牌共入选 " . ($brandRankingCntMap[$brandId] ?? 0) . " 个榜单",
                        'total_ranking' => ($brandRankingCntMap[$brandId] ?? 0),
                        'link' => Hhzurl::getDomain() . Ranking::BRAND_URL . "?brand_id=" . $brandId . '&act_from=brand_zone',
                    ];
                    $brandInfo = [
                        'type' => BlockType::TYPE_BRAND_LIST,
                        'brand' => $brand,
                        "statSign" => statSign::genStatSign(statSign::MODULE_BRAND_ZONE_CATEGORY_BRAND_LIST, [
                            statSign::EXTEND_KEY_OBJ_ID => $brandId,
                            statSign::EXTEND_KEY_INDEX => $sort,
                            'page' => statSign::EXTEND_KEY_PAGE,
                        ], ['module_name' => '发现品牌-品牌列表', 'tab_name' => $classify_name, 'tab_id' => $classify_id, 'uid' => $this->uid]),
                    ];
                    if (!is_null($insertIndex) && !is_null($insertIndexBrandId) && $brandId == $insertIndexBrandId) {
                        $insertBrandInfo = $brandInfo;
                    } else {
                        $brand_list[] = $brandInfo;
                    }
                    $sort++;
                }
            }
        }
        if ($classify_id == !self::MY_FOCUS) {
            rsort($brand_list);
        }
        if (!is_null($insertIndex) && !is_null($insertIndexBrandId) && $insertBrandInfo) {
            array_splice($brand_list, $insertIndex, 0, [$insertBrandInfo]);
        }
        $data['list'] = array_values($brand_list);

        ActionLog::log($this->uid, ['page' => $page, 'title' => $classify_name, 'tab_id' => $classify_id],
            ActionLog::PAGE_FIND_BRAND);
        $this->setSuccess($data);
    }

    /**
     * @param int $page
     * @return array
     */
    public function myFocusBrand(int $page): array
    {
        $uidArr = MyFocus::getMyFocusUidArr($this->uid, Member::AUTH_USER_BRAND);
        $list = [];
        $count = 0;
        if ($uidArr) {
            $where = [
                'uid' => $uidArr,
                'ORDER' => ['uid' => $uidArr],
                'LIMIT' => [($page - 1) * (self::DEFAULT_PAGESIZE), (self::DEFAULT_PAGESIZE)],
            ];
            $list = Brand::getBrandByFilter($where, ['id(obj_id)']);
            unset($where['LIMIT']);
            $count = Brand::getCountByWhere($where);
        }

        return [
            'list' => $list,
            'total_num' => $count,
        ];

    }

    /**
     * @param $wikis
     * @param $classifyId
     * @return array
     */
    public function handleWiki($wikis, $classifyId): array
    {
        $res = [];
        if ($wikis) {
            foreach ($wikis as $wiki) {
                $wiki['statSign'] = statSign::genStatSign(statSign::MODULE_BRAND_ZONE_BRAND_RECOMMEND_WIKI, [
                    statSign::EXTEND_KEY_OBJ_ID => $wiki['id'],
                    statSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI,
                ], [
                    'uid' => $this->uid,
                    'basic_id' => $wiki['basic_id'],
                    'brand_id' => $wiki['brand_id'],
                    'classify_id' => $classifyId,

                ]);
                $res [] = $wiki;
            }
        }

        return $res;
    }

    private function showTclIndex($page, $classify_id)
    {
        $index = null;
        $indexBrandId = null;
        $today = (int)date('Ymd');
        if ($page == 1) {
            if ($today >= 20231115 && $today <= 20231129) {
                if ($classify_id == self::POPULAR_BRANDS) {
                    $index = 0;//第一位，插入tcl品牌
                    $indexBrandId = 483;//tcl 品牌id
                } else if ($classify_id == 530) {//家电分类
                    $index = 0;//第一位，插入tcl品牌
                    $indexBrandId = 483;//tcl 品牌id
                }
            }
        }
        return [$index, $indexBrandId];
    }
}
